import mongoose from 'mongoose';
import { ApolloServer} from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import typeDefs from './graphql/typeDefs';
import { resolvers } from './graphql/resolvers';
import { MONGODB } from './config';
import User from './Models/User';
mongoose.set({ strictQuery: true })
const server = new ApolloServer({
  typeDefs,
  resolvers,
})
mongoose
  .connect(MONGODB)
  .then(() => {
    console.log('mongoDB connected')
    return startStandaloneServer(server, {
      context: async ({ req }) => ({ req }),
      listen: { port: 5001 },
    });
  })
  .then((res) => {
    console.log(`server running at ${res.url}`)
    // 默认写入 管理员账号和顾客用户账号
    insertInitualUser()
  })
  .catch((err) => {
    console.log(err.message)
  })

const insertInitualUser = async () => {
  // 创建顾客用户
  const customer = await User.findOne({ username: 'customer' })
  if (!customer) {
    const modelUser = {
      username: 'customer',
      name: 'Allen Wang',
      password: '$2b$12$E3HhmKVLByKt2dpXIMWih.Ot4tUYku15ArVc7qcaC8LXqCWdSe6sW',
      phone: '18666668880',
      createdAt: new Date().toISOString(),
      type: 'customer',
    }
    const initCustomers = new Array(4).fill(null).map((_, idx: number) => {
      idx = idx > 0 ? idx : -1
      return {
        ...modelUser,
        username: modelUser.username + idx,
        phone: (parseInt(modelUser.phone) + idx).toString(),
        name: modelUser.name + idx,
      }
    })
    await User.insertMany(initCustomers)
  }
  const admin = await User.findOne({ type: 'admin' })
  if (!admin) {
    const newCustomer = new User({
      username: 'admin',
      name: 'LiLy',
      password: '$2b$12$E3HhmKVLByKt2dpXIMWih.Ot4tUYku15ArVc7qcaC8LXqCWdSe6sW',
      phone: '18899998888',
      createdAt: new Date().toISOString(),
      type: 'admin',
    })
    await newCustomer.save()
  }
}
